package com.example.service;

import com.example.entity.Role;
import com.example.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class RoleService {

    @Autowired
    private RoleMapper roleMapper;

    public Role findRoleWithMenusById(Long roleId) {
        return roleMapper.findRoleWithMenusById(roleId);
    }

    public List<Role> findAllRolesWithMenus(Integer offset, Integer pageSize) {
        return roleMapper.findAllRolesWithMenus(offset, pageSize);
    }

    public Long countAllRoles() {
        return roleMapper.countAllRoles();
    }

    public Role findRoleByName(String roleName) {
        return roleMapper.findRoleByName(roleName);
    }

    // 任务四：更新角色菜单权限 - 增强事务管理
    @Transactional(rollbackFor = Exception.class)
    public void updateRoleMenus(Long roleId, List<Long> menuIds) {
        // 删除角色现有菜单
        roleMapper.deleteRoleMenus(roleId);

        // 添加新菜单
        if (menuIds != null && !menuIds.isEmpty()) {
            for (Long menuId : menuIds) {
                roleMapper.addRoleMenu(roleId, menuId);
            }
        }
    }
}
